{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>库存数据对比系统</title>

    <!-- Bootstrap 5.3 CSS -->
    <link href="{% static 'plugins/bootstrap-5.3.0-alpha1-dist/css/bootstrap.min.css' %}" rel="stylesheet">

    <!-- 自定义样式 -->
    <style>
        body {
            background-color: #f8f9fa;
            padding-top: 2rem;
        }

        .filter-box {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 0.125rem 0.75rem rgba(0,0,0,0.05);
            margin-bottom: 1.5rem;
        }

        .filter-item {
            margin-right: 1rem;
            margin-bottom: 1rem;
            display: inline-block;
            vertical-align: top;
        }

        .data-table th {
            background-color: #e9ecef !important;
            min-width: 140px;
        }

        .highlight {
            background-color: #fff3cd !important;
        }

        .table-responsive {
            max-height: 60vh;
            overflow-y: auto;
        }

        .spinner-border {
            width: 3rem;
            height: 3rem;
        }

        #dataStats {
            font-size: 0.9rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 上传表单 -->
        <div class="card mb-4 shadow-sm">
            <div class="card-body">
                <h4 class="card-title mb-4">库存数据对比系统</h4>
                <form id="uploadForm" enctype="multipart/form-data">
                    {% csrf_token %}
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="wms_file" class="form-label">WMS收发存报表</label>
                            <input type="file" class="form-control" name="wms_file" id="wms_file"
                                   required accept=".xlsx,.xls">
                        </div>
                        <div class="col-md-6">
                            <label for="erp_file" class="form-label">ERP收发存报表</label>
                            <input type="file" class="form-control" name="erp_file" id="erp_file"
                                   required accept=".xlsx,.xls">
                        </div>
                    </div>
                    <div class="mt-3 d-grid gap-2 d-md-flex justify-content-md-end">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-upload me-1"></i> 开始对比分析
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 加载提示 -->
        <div id="loading" class="text-center my-4" style="display:none;">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-3">数据正在分析中，请稍候...</p>
        </div>

        <!-- 筛选条件 -->
        <div id="filter-section" style="display:none;" class="mb-4">
            <div class="filter-box">
                <h5 class="mb-3">数据筛选条件</h5>
                <div class="d-flex flex-wrap align-items-center gap-3">
                    <div class="filter-item">
                        <label class="form-label">差异量绝对值 ≥</label>
                        <input type="number" id="diffFilter" min="0" value="0"
                               class="form-control" style="width: 120px;">
                    </div>
                    <div class="filter-item">
                        <label class="form-label">对比结果：</label>
                        <select id="resultFilter" class="form-select" style="width: 150px;">
                            <option value="all">全部结果</option>
                            <option value="一致">数据一致</option>
                            <option value="不一致">数据不一致</option>
                        </select>
                    </div>
                    <div class="filter-item">
                        <label class="form-label">排序方式：</label>
                        <select id="sortBy" class="form-select" style="width: 180px;">
                            <option value="default">默认顺序</option>
                            <option value="diff_desc">差异量（从大到小）</option>
                            <option value="diff_asc">差异量（从小到大）</option>
                            <option value="name">物品名称排序</option>
                        </select>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-success" onclick="applyFilters()">
                            <i class="bi bi-funnel-fill me-1"></i> 应用筛选
                        </button>
                        <button class="btn btn-secondary" onclick="resetFilters()">
                            <i class="bi bi-arrow-counterclockwise me-1"></i> 重置条件
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据展示区域 -->
        <div id="result-section" style="display:none;">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h5 class="card-title mb-3">详细库存对比数据</h5>
                    <div class="table-responsive">
                        <table class="table table-hover table-bordered data-table align-middle">
                            <thead class="table-light" id="tableHeader"></thead>
                            <tbody id="tableBody"></tbody>
                        </table>
                    </div>
                    <div class="mt-3" id="dataStats"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS + Popper -->
    <script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-5.3.0-alpha1-dist/js/bootstrap.bundle.min.js' %}"></script>

    <!-- 自定义脚本 -->
    <script>
        let rawData = [];
        let currentSort = 'default';

        function applyFilters() {
            const minDiff = parseInt(document.getElementById('diffFilter').value) || 0;
            const resultFilter = document.getElementById('resultFilter').value;
            currentSort = document.getElementById('sortBy').value;

            let filteredData = rawData.filter(item => {
                const diff = Math.abs(parseFloat(item['差异量']));
                const resultMatch = resultFilter === 'all' || item['对比结果'] === resultFilter;
                return diff >= minDiff && resultMatch;
            });

            switch(currentSort) {
                case 'diff_desc':
                    filteredData.sort((a,b) => Math.abs(b.差异量) - Math.abs(a.差异量));
                    break;
                case 'diff_asc':
                    filteredData.sort((a,b) => Math.abs(a.差异量) - Math.abs(b.差异量));
                    break;
                case 'name':
                    filteredData.sort((a,b) => a.物品名称.localeCompare(b.物品名称));
                    break;
            }

            renderTable(filteredData);
            updateStats(filteredData);
        }

        function resetFilters() {
            document.getElementById('diffFilter').value = 0;
            document.getElementById('resultFilter').value = 'all';
            document.getElementById('sortBy').value = 'default';
            applyFilters();
        }

        function renderTable(data) {
            const tbody = document.getElementById('tableBody');
            tbody.innerHTML = '';
            data.forEach(row => {
                const tr = document.createElement('tr');
                if (row['对比结果'] === '不一致') tr.classList.add('highlight');

                ['物品名称', 'WMS数量', 'ERP数量', '差异量', '对比结果'].forEach(key => {
                    const td = document.createElement('td');
                    td.textContent = key === '差异量' ? row[key].toFixed(2) : row[key];
                    td.style.fontWeight = key === '差异量' ? 'bold' : 'normal';
                    td.style.color = key === '差异量' && row[key] !== 0 ? '#dc3545' : '';
                    tr.appendChild(td);
                });

                tbody.appendChild(tr);
            });
        }

        function updateStats(data) {
            const total = data.length;
            const mismatch = data.filter(d => d.对比结果 === '不一致').length;
            const maxDiff = Math.max(...data.map(d => Math.abs(d.差异量)));
            document.getElementById('dataStats').innerHTML = `
                当前显示：<strong>${total}</strong> 条记录 |
                差异项：<strong>${mismatch}</strong> 条 |
                最大差异量：<strong>${maxDiff.toFixed(2)}</strong>
            `;
        }

        document.getElementById('uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const loading = document.getElementById('loading');
            const resultSection = document.getElementById('result-section');
            const filterSection = document.getElementById('filter-section');

            loading.style.display = 'block';
            resultSection.style.display = 'none';
            filterSection.style.display = 'none';

            fetch('', {
                method: 'POST',
                body: formData,
                headers: {'X-Requested-With': 'XMLHttpRequest'}
            })
            .then(response => response.json())
            .then(data => {
                loading.style.display = 'none';
                if (data.status === 'success') {
                    rawData = JSON.parse(data.raw_data);
                    filterSection.style.display = 'block';
                    resultSection.style.display = 'block';

                    // 渲染表头
                    const thead = document.getElementById('tableHeader');
                    thead.innerHTML = `
                        <tr>
                            <th>物品名称</th>
                            <th>WMS数量</th>
                            <th>ERP数量</th>
                            <th>差异量</th>
                            <th>对比结果</th>
                        </tr>
                    `;

                    applyFilters(); // 初始渲染

                    // 自动下载 Excel 文件
                    const byteArray = Uint8Array.from(atob(data.excel.data), c => c.charCodeAt(0));
                    const blob = new Blob([byteArray], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = data.excel.filename;
                    link.click();
                    URL.revokeObjectURL(link.href);

                } else {
                    alert('处理失败: ' + data.message);
                }
            })
            .catch(error => {
                loading.style.display = 'none';
                alert('请求失败: ' + error.message);
            });
        });
    </script>
</body>
</html>